﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PetaPoco;
using WebAppMatrix.Data;

namespace WebAppMatrix.DAL
{
    public class BaseRepository<T> : IRepository<T> where T : class ,new()
    {
        /// <summary>
        /// 初始化
        /// </summary>
        private MatrixData database = null;
        public MatrixData Database
        {
            get
            {
                if (database == null)
                {
                    database = new MatrixData(WebAppMatrix.MatrixManager.Settings.ConnectionStringName);
                }

                return database;
            }
        }

        public BaseRepository(MatrixData database)
        {
            this.database = database;
        }

        public virtual List<T> GetAll()
        {
            return Database.Query<T>("").ToList();
        }

        public virtual T GetSingle(object id)
        {
            return Database.SingleOrDefault<T>(id);
        }

        public virtual T GetFirst(string sql, params object[] args)
        {
            return Database.FirstOrDefault<T>(sql, args);
        }

        public virtual List<T> GetList(string sql, params object[] args)
        {
            return Database.Fetch<T>(sql, args);
        }

        public virtual void Insert(T entity)
        {
            Database.Insert(entity);
        }

        public virtual void Update(T entity)
        {
            Database.Update(entity);
        }

        public virtual void Delete(T entity)
        {
            Database.Delete(entity);
        }

        public virtual Page<T> Page(long page, long rows, string sql, params object[] args)
        {
            return Database.Page<T>(page, rows, sql, args);
        }
    }
}
